<template>
  <div>
    <!-- 导航栏 -->
    <NavBar />
    <UserInfo />
    
    <!-- 搜索框 -->
    <div class="search-bar">
      <select v-model="searchType">
        <option value="product">Product</option>
        <option value="store">Store</option>
        <option value="category">Category</option>
      </select>
      <input class="search-input" @input="debounce" v-model="searchQuery" type="text" placeholder="Please enter the product or store you want to search for" />
      <button @click="search">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
          <path d="M10 2a8 8 0 016.32 12.906l4.387 4.387-1.414 1.414-4.387-4.387A8 8 0 1110 2zm0 2a6 6 0 100 12 6 6 0 000-12z"></path>
        </svg>
      </button>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <h2>All Products</h2>
      <div v-if="products.length === 0">No products available</div>
      <div v-else class="product-grid">
        <div v-for="product in products" :key="product.id" class="product-item">
          <!-- <div v-if="axios.get(`${product.image}`).catch(()=>{return false})">
          <img :src="product.image" :alt="product.goodsName" class="product-image" />
          </div>
          <div v-else>
            <img src="https://avatars.mds.yandex.net/i?id=94e1ac21200e722e68add82c7451d22c6da8f43f-5869113-images-thumbs&n=13" :alt="product.goodsName" class="product-image" />
          </div> -->
          <img
            :src="product.image"
            :alt="product.goodsName"
            class="product-image"
            @error="handleImageError"
          />
          <div class="product-info">
            <div class="product-type">{{ product.category || 'General' }}</div>
            <h3 class="product-name">{{ product.goodsName }}</h3>
            <div class="price-section">
              <span class="price-label">Price:</span>
              <span class="price-value">¥{{ product.price.toFixed(2) }}</span>
            </div>
            <button @click="addToCart(product)" class="add-to-cart-btn">
              Add to Cart
            </button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="showSuccess" class="add-feedback">
      <div class="feedback-content">
        <span>✔ Added </span>
        <strong>{{ addedProduct?.name }}</strong>
        <span> to cart successfully!</span>
      </div>
    </div>

    <!-- 购物车图标 -->
    <div class="cart-icon" @click="goToCart">
      🛒
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { fetchProducts, searchProductsOrStores } from "../api/auth";
import NavBar from "@/components/NavBar.vue";
import store from '../store';
import UserInfo from "@/components/UserInfo.vue";
const router = useRouter();
const searchQuery = ref("");
const searchType = ref("product");
let products = ref([]);
const addedProduct = ref(null);
const showSuccess = ref(false);
const handleImageError = (event) => {
  event.target.src = 'https://avatars.mds.yandex.net/i?id=94e1ac21200e722e68add82c7451d22c6da8f43f-5869113-images-thumbs&n=13';
}
const addToCart = async (product) => {
  try {
    const response = await axios.post("http://localhost:8080/api/cart/add", null, {
      params: {
        userName: store.getters['user/username'],
        goodsId: product.goodsId,
        number: 1,
        price: product.price,
      }
    });
    console.log(response);
    addedProduct.value = product;
    showSuccess.value = true;
    setTimeout(() => showSuccess.value = false, 3000);
    
    console.log("添加购物车成功:", response.data);
  } catch (error) {
    
    console.error("添加购物车失败:", error);
    alert("Failed to add product to cart");
  }
};

const loadProducts = async () => {
  const username = store.getters['user/username'];
  if(!username){
    alert("Please login first");
    router.push("/userLogin");
    return;
  }
  try {
    const response = await fetchProducts();
    products.value = response.data || [];
    ordermap(products.value);

    console.log('orderid:',store.getters['seller/orderid']);
  } catch (error) {
    console.error("Failed to load products:", error);
  }
};

const ordermap = (value) => {
  console.log(value);
    var orderid = new Map();
    var goodsname = new Map();
    for(let item of value){
      orderid.set(item.goodsId, item.sellerName);
      goodsname.set(item.goodsId, item.goodsName);
    }
    console.log(orderid);
    store.dispatch('seller/setOrderid', orderid);
    store.dispatch('seller/setGoodsname', goodsname);
};

const debounce = () => {
  let timer = null;
  {
    if(timer){
      clearTimeout(timer);
    }
    timer = setTimeout(()=>{
      search();
      timer = null;
    },1000);
  }
}

const search = async () => {
  if (!searchQuery.value.trim()) {
    loadProducts();
    return;
  }
  try {
    if(searchType.value==='category'){
      var response = new axios.post(`http://localhost:8080/api/category?category=${searchQuery.value.trim()}`,{
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      }).then(response=>{
        console.log(response);
        products.value = response.data || [];
      }).catch(error=>{
        console.error("Failed to load products:", error);
      })
    }
    else{
      response = await searchProductsOrStores(searchType.value, searchQuery.value.trim());
      products.value = response || [];
    }
  } catch (error) {
    console.error("Search failed:", error);
  }
};

const goToCart = () => {
  router.push("/shoppingCart");
};

onMounted(loadProducts);
</script>

<style scoped>
/* 搜索框样式保持不变 */
.search-bar {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 1000px;
  margin: 35px auto;
  padding: 15px;
  border: 2px solid black;
  border-radius: 25px;
  background-color: #fff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.search-bar select {
  font-weight: bold;
  padding: 12px;
  border: 2px solid white;
  border-radius: 20px;
  font-size: 18px;
  background-color: white;
  cursor: pointer;
  margin-right: 10px;
  outline: none;
}
.search-bar input {
  flex: 1;
  padding: 15px;
  border: none;
  border-radius: 30px;
  outline: none;
  font-size: 18px;
}
.search-bar button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  padding: 15px 15px;
  border-radius: 50%;
  transition: background-color 0.3s;
}
.search-bar button:hover {
  background-color: #f0f0f0;
}
.search-bar svg {
  width: 24px;
  height: 24px;
  fill: #333;
}

/* 商品列表样式 - 美化部分 */
.product-list {
  width: 90%;
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.product-list h2 {
  font-size: 28px;
  color: #2d3748;
  margin-bottom: 25px;
  font-weight: 700;
  text-align: center;
  position: relative;
  padding-bottom: 10px;
}

.product-list h2::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, #4299e1, #9f7aea);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 25px;
}

.product-item {
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
  border-color: #cbd5e0;
}

.product-item::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #4299e1, #9f7aea);
}

.product-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-item:hover .product-image {
  transform: scale(1.03);
}

.product-info {
  padding: 16px;
  position: relative;
}

.product-type {
  font-size: 12px;
  color: #718096;
  background: #f7fafc;
  padding: 4px 10px;
  border-radius: 20px;
  display: inline-block;
  margin-bottom: 10px;
  font-weight: 500;
  letter-spacing: 0.5px;
  text-transform: uppercase;
}

.product-name {
  font-size: 16px;
  margin: 8px 0;
  color: #2d3748;
  font-weight: 600;
  line-height: 1.4;
  min-height: 44px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-section {
  display: flex;
  align-items: center;
  margin: 12px 0 15px;
  justify-content: space-between;
}

.price-label {
  font-size: 13px;
  color: #718096;
  font-weight: 500;
}

.price-value {
  font-size: 18px;
  color: #2b6cb0;
  font-weight: 700;
}

.add-to-cart-btn {
  width: 100%;
  background: linear-gradient(90deg, #4299e1, #38b2ac);
  color: white;
  padding: 10px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.add-to-cart-btn:hover {
  background: linear-gradient(90deg, #3182ce, #319795);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(66, 153, 225, 0.3);
}

.add-to-cart-btn::before {
  content: "+";
  font-size: 16px;
  font-weight: bold;
}

/* 反馈信息和购物车图标样式保持不变 */
.add-feedback {
  position: fixed;
  bottom: 150px;
  right: 20px;
  background: #4CAF50;
  color: white;
  padding: 12px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  z-index: 100;
  animation: slideIn 0.3s ease-out;
}
.feedback-content {
  display: flex;
  align-items: center;
  gap: 5px;
}
.cart-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  font-size: 50px;
  color: white;
  background-color: orangered;
  border: 1px solid red;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
.cart-icon:hover {
  transform: scale(1.1);
}

@keyframes slideIn {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>